//
//  THToolBase.m
//  THImageEditDemo
//
//  Created by 希达 on 2018/3/28.
//  Copyright © 2018年 Tan.huang. All rights reserved.
//

#import "THToolBase.h"
#import "THFilterModel.h"

@interface THToolBase() <UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;
@end

@implementation THToolBase

- (id)initWithImageEditor:(THImageEditViewController *)editor{
    self = [super init];
    if (self) {
        self.editor = editor;

        self.imageArray = [NSMutableArray array];
    }
    return self;
}

- (UIView *)bgView {
    if (_bgView == nil) {
        UIView *bgView = [[UIView alloc] initWithFrame:self.editor.bgView.bounds];
        bgView.backgroundColor = [UIColor whiteColor];
        _bgView = bgView;
    }
    return _bgView;
}

- (UIView *)workingView {
    if (_workingView == nil) {
        UIView *workingView = [[UIView alloc] initWithFrame:[self.editor.view convertRect:self.editor.imageView.frame fromView:self.editor.imageView.superview]];
        workingView.clipsToBounds = YES;
        _workingView = workingView;
    }
    return _workingView;
}

- (LxGridView *)collectionView {
    if (_collectionView == nil) {
        CGFloat width = self.editor.bgView.frame.size.width;
        CGFloat btnWidth = (width - 50) / 4;
        LxGridViewFlowLayout *flowLayout = [[LxGridViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(btnWidth, btnWidth + 20);
        LxGridView *collectionView = [[LxGridView alloc] initWithFrame:CGRectMake(0, 0, width, btnWidth + 20) collectionViewLayout:flowLayout];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[THEditImgCell class] forCellWithReuseIdentifier:@"THEditImgCell"];
        [collectionView registerClass:[THImgCollectionViewCell class] forCellWithReuseIdentifier:@"THImgCollectionViewCell"];
        _collectionView = collectionView;
    }
    return _collectionView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.imageArray.count == indexPath.item) {
        THImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"THImgCollectionViewCell" forIndexPath:indexPath];
        @weakify(self);
        [cell setAddBtnClickBlock:^{
            @strongify(self);
            NSLog(@"添加图片");
            [self presentImagePickerController];
        }];
        return cell;
    } else {
        THEditImgCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"THEditImgCell" forIndexPath:indexPath];
        cell.editing = self.collectionView.editing;
        cell.model = self.imageArray[indexPath.item];
        @weakify(self);
        [cell setDeleBtnClickBlock:^(UICollectionViewCell *cell) {
            @strongify(self);
            NSIndexPath *editImgCellIndexPath = [collectionView indexPathForCell:cell];
            if (editImgCellIndexPath) {
                [self.imageArray removeObjectAtIndex:editImgCellIndexPath.item];
                [collectionView performBatchUpdates:^{
                    [collectionView deleteItemsAtIndexPaths:@[editImgCellIndexPath]];
                } completion:^(BOOL finished) {
                    self.collectionView.editing = NO;
                }];
            }
        }];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if ([cell isMemberOfClass:[THEditImgCell class]]) {
        THEditImgCell *editImgCell = (THEditImgCell *)cell;
        self.editor.imageView.image = editImgCell.imageView.image;
    }
}

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < self.imageArray.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < self.imageArray.count && destinationIndexPath.item < self.imageArray.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath willMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    THTextureModel *model = self.imageArray[sourceIndexPath.item];
    [self.imageArray removeObjectAtIndex:sourceIndexPath.item];
    [self.imageArray insertObject:model atIndex:destinationIndexPath.item];
}

- (void)presentImagePickerController{
    //调用系统相册的类
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    //设置相册呈现的样式
    pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //图片分组列表样式
    //照片的选取样式还有以下两种
    //UIImagePickerControllerSourceTypePhotoLibrary,直接全部呈现系统相册
    //UIImagePickerControllerSourceTypeCamera
    pickerController.delegate = self;
    [self.editor presentViewController:pickerController animated:YES completion:nil];
}
    
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo NS_DEPRECATED_IOS(2_0, 3_0) {
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.addView) {
        [self.addView removeFromSuperview];
    }
    NSLog(@"%@",info);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *resultImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        THAddImageView *addImageView = [[THAddImageView alloc] initWithFrame:CGRectMake(self.editor.imageView.width * 0.5 - 50, self.editor.imageView.height * 0.5 - 50, 100, 100)];
        addImageView.image = resultImage;
        [self.workingView addSubview:addImageView];
        
        @weakify(self);
        [addImageView setTapGestureClickBlock:^(THAddImageView *imgView) {
            @strongify(self);
            self.addView = imgView;
            [self presentImagePickerController];
        }];
    } else {
//        [self.editor showHint:@""];
    }
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
    

- (void)setup {
    for (int i = 0; i < 2; i ++) {
        THTextureModel *model = [[THTextureModel alloc] init];
        model.name = [NSString stringWithFormat:@"第%d个", i];
        model.img = [NSString stringWithFormat:@"icon_%d", i];
        model.isDele = YES;
        [self.imageArray addObject:model];
    }

    [self.editor.bgView addSubview:self.bgView];
    [self.bgView addSubview:self.collectionView];
    [self.editor.view addSubview:self.workingView];
    [self.collectionView reloadData];
}

- (void)cleanup {
    
}


/// 缩放动画
- (void)affineTransformScale:(UIView *)view toView:(UIView *)toView isShow:(BOOL)isShow {
    if (isShow) {
        if (toView) {
            toView.transform = CGAffineTransformMakeScale(0.5, 0.5);
            toView.alpha = 0;
        }
//        if (view) {
//            view.transform = CGAffineTransformIdentity;
//            view.alpha = 1;
//        }
        [UIView animateWithDuration:kTHImageToolAnimationDuration animations:^{
            if (view) {
                view.transform = CGAffineTransformMakeScale(0.5, 0.5);
                view.alpha = 0;
            }
            if (toView) {
                toView.transform = CGAffineTransformIdentity;
                toView.alpha = 1;
            }
        }];
    } else {
//        if (toView) {
//            toView.transform = CGAffineTransformIdentity;
//            toView.alpha = 1;
//        }
        if (view) {
            view.transform = CGAffineTransformMakeScale(0.5, 0.5);
            view.alpha = 0;
        }
        [UIView animateWithDuration:kTHImageToolAnimationDuration animations:^{
            if (view) {
                view.transform = CGAffineTransformIdentity;
                view.alpha = 1;
            }
            if (toView) {
                toView.transform = CGAffineTransformMakeScale(0.5, 0.5);
                toView.alpha = 0;
            }
        }];
    }
}


- (UIImage*)buildImage:(UIImage*)image
{
    __block CALayer *layer = nil;
    __block CGFloat scale = 1;

    safe_dispatch_sync_main(^{
        scale = image.size.width / self.workingView.width;
        layer = self.workingView.layer;
    });

    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);

    [image drawAtPoint:CGPointZero];

    CGContextScaleCTM(UIGraphicsGetCurrentContext(), scale, scale);
    [layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *tmp = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return tmp;
}

//获取屏幕截屏方法
- (UIImage *)capture:(UIView *)view {
    // 创建一个context
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    //把当前的全部画面导入到栈顶context中并进行渲染
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    // 从当前context中创建一个新图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return img;
}


- (void)dealloc {
    NSLog(@"%@ 释放了", NSStringFromClass(self.class));
}

@end
